package com.tanhua.server.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.ConclusionEnum;
import com.tanhua.common.enums.CoverEnum;
import com.tanhua.common.mapper.SoulReportMapper;
import com.tanhua.common.pojo.SoulDimensions;
import com.tanhua.common.pojo.SoulReport;
import com.tanhua.common.pojo.SoulSimilarYou;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.server.vo.ConclusionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import com.tanhua.common.mapper.*;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.vo.OptionsVo;
import com.tanhua.server.vo.PaperListVo;
import com.tanhua.server.vo.QuestionsVo;
import cn.hutool.core.util.ObjectUtil;
import com.tanhua.common.mapper.SoulOptionsMapper;
import com.tanhua.common.mapper.SoulPaperQuestionMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * tb_souloptions   用来设置每个题目的选项（题库插入）
 * <p>
 * tb_soulpaper     用来设置题目的类型（固定）
 * <p>
 * tb_soulpaperquestion   组成试卷表
 * <p>
 * tb_soulquestion   题目表（题库插入）
 * <p>
 * tb_soulreport   报告表
 */


@Service
@Slf4j
@SuppressWarnings("ALL")
public class TestSoulService {

    @Autowired
    private SoulReportMapper soulReportMapper;

    @Autowired
    private SoulPaperMapper soulPaperMapper;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulPaperQuestionMapper soulPaperQuestionMapper;

    @Autowired
    private SoulOptionsMapper soulOptionsMapper;

    @Autowired
    UserInfoService userInfoService;

    /**
     * @MethodName: getReport
     * @Description: 测灵魂-查看结果
     * @Author liuwei
     * @Param
     * @PReturn
     * @Date 2021/4/27
     * @Time 11:48
     */
    public ConclusionVo getReport(String id) {
        //创建ConclusionVo对象
        ConclusionVo conclusionVo = new ConclusionVo();
        //先根据报告id获取report表中的数据
        QueryWrapper<SoulReport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        SoulReport soulReport = soulReportMapper.selectOne(queryWrapper);
        //如果report表中没有数据,返回null
        if (null == soulReport) {
            return null;
        }
        //从report表中获取用户的得分
        Long score = soulReport.getScore();
        //再到report表中查询分数接近的用户

        QueryWrapper<SoulReport> queryListWrapper = new QueryWrapper<>();
        queryListWrapper.between("score", score - 5, score + 5).ne("userid",soulReport.getUserid()).eq("paperid",soulReport.getPaperid());

        List<SoulReport> soulReportList = soulReportMapper.selectList(queryListWrapper);
        //获取这些分数接近的用户的id
        List<Object> userIdList = CollUtil.getFieldValues(soulReportList, "userid");
        //获取userinfo对象的集合
        List<UserInfo> userInfoList = new ArrayList<>();
        if (CollUtil.isNotEmpty(userIdList)) {
            userInfoList = userInfoService.queryUserInfoByUserIdList(userIdList);
        }
        //遍历userinfo集合,创建soulsimilar对象,并创建集合
        List<SoulSimilarYou> similarYouList = new ArrayList<>();
        if (null != userInfoList) {
            for (UserInfo userInfo : userInfoList) {
                SoulSimilarYou soulSimilarYou = new SoulSimilarYou();
                soulSimilarYou.setAvatar(userInfo.getLogo());
                soulSimilarYou.setId(Convert.toInt(userInfo.getId()));
                similarYouList.add(soulSimilarYou);
            }
        }
        if (21 > score) {
            //小于21分,鉴定结果为理性
            conclusionVo.setConclusion(ConclusionEnum.MAOTOUTING.getValue());
            conclusionVo.setCover(CoverEnum.MAOTTOUYING.getValue());
            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("外向", "60%");
            SoulDimensions s2 = new SoulDimensions("判断", "80%");
            SoulDimensions s3 = new SoulDimensions("抽象", "70%");
            SoulDimensions s4 = new SoulDimensions("理性", "90%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        } else if (21 <= score && score <= 40) {
            //21-40分,鉴定结果为判断类型
            conclusionVo.setConclusion(ConclusionEnum.BAITU.getValue());
            conclusionVo.setCover(CoverEnum.BAITU.getValue());

            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("外向", "80%");
            SoulDimensions s2 = new SoulDimensions("判断", "60%");
            SoulDimensions s3 = new SoulDimensions("抽象", "70%");
            SoulDimensions s4 = new SoulDimensions("理性", "90%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);

            //conclusionVo.setDimensions(Convert.toList(new SoulDimensions("判断", "70%")));
            conclusionVo.setSimilarYou(similarYouList);
        } else if (41 <= score && score <= 55) {
            //41-55分,鉴定结果为抽象类型
            conclusionVo.setConclusion(ConclusionEnum.HULI.getValue());
            conclusionVo.setCover(CoverEnum.HULI.getValue());
            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("外向", "80%");
            SoulDimensions s2 = new SoulDimensions("判断", "70%");
            SoulDimensions s3 = new SoulDimensions("抽象", "60%");
            SoulDimensions s4 = new SoulDimensions("理性", "90%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        } else if (score > 56) {
            //41-55分,鉴定结果为外向类型
            conclusionVo.setConclusion(ConclusionEnum.SHIZI.getValue());
            conclusionVo.setCover(CoverEnum.SHIZI.getValue());
            List<SoulDimensions> dimensionsList = new ArrayList<>();
            SoulDimensions s1 = new SoulDimensions("外向", "90%");
            SoulDimensions s2 = new SoulDimensions("判断", "70%");
            SoulDimensions s3 = new SoulDimensions("抽象", "80%");
            SoulDimensions s4 = new SoulDimensions("理性", "60%");
            dimensionsList.add(s1);
            dimensionsList.add(s2);
            dimensionsList.add(s3);
            dimensionsList.add(s4);
            conclusionVo.setDimensions(dimensionsList);
            conclusionVo.setSimilarYou(similarYouList);
        }
        //ConclusionVo填充完毕,进行返回
        return conclusionVo;
    }

    /**
     * 测灵魂-问卷列表
     *
     * @return
     */
    public List<PaperListVo> queryPaperList() {
        User user = UserThreadLocal.get();

        //先查询试卷表，得出试卷的id的集合，遍历集合结合用户id判断用户应该做哪一种类型的试卷
        //初级灵魂试题肯定是不能锁住的，只有中级灵魂试题和高级灵魂试题才能锁住

        //构造返回的页面对象
        PaperListVo paperListVo1 = new PaperListVo();
        PaperListVo paperListVo2 = new PaperListVo();
        PaperListVo paperListVo3 = new PaperListVo();


        //构造查询报告的条件
        QueryWrapper<SoulReport> soulReportQueryWrapper = new QueryWrapper<>();
        soulReportQueryWrapper.eq("userid", user.getId());

        //查找报告
        List<SoulReport> soulReports = soulReportMapper.selectList(soulReportQueryWrapper);
        int size = soulReports.size();
        //设置问卷id
        //Long WJID=Convert.toLong(size+1);

        /*QueryWrapper<SoulPaperQuestion> queryWrapper1 = new QueryWrapper<>();
        QueryWrapper<SoulPaperQuestion> queryWrapper2 = new QueryWrapper<>();
        QueryWrapper<SoulPaperQuestion> queryWrapper3 = new QueryWrapper<>();*/


        commendMethod1(paperListVo1, 1);
        commendMethod1(paperListVo2, 2);
        commendMethod1(paperListVo3, 3);

        //判断报告id是否为空,肯定是初级的
        if (size == 0) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(1);
            paperListVo3.setIsLock(1);
            //设置报告id
            /*for (SoulReport soulReport : soulReports) {
                if (soulReport.getPaperid() == 1) {
                    paperListVo1.setReportId(soulReport.getId().toString());
                }
            }*/
            //soulReports.forEach(soulReport -> paperListVo1.setReportId(soulReport.getId().toString()));

        } else if (soulReports.size() == 1) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(1);
            //设置报告id
            for (SoulReport soulReport : soulReports) {
                if (soulReport.getPaperid() == 1) {
                    paperListVo1.setReportId(soulReport.getId().toString());
                }
                paperListVo2.setReportId(null);
                paperListVo3.setReportId(null);

            }
            //soulReports.forEach(soulReport -> paperListVo2.setReportId(soulReport.getId().toString()));
        } else if (soulReports.size() == 2) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(0);
            //设置报告id
            for (SoulReport soulReport : soulReports) {
                if (soulReport.getPaperid() == 1) {
                    paperListVo1.setReportId(soulReport.getId().toString());
                }if (soulReport.getPaperid() == 2) {
                    paperListVo2.setReportId(soulReport.getId().toString());
                }
                paperListVo3.setReportId(null);
            }
            //soulReports.forEach(soulReport -> paperListVo3.setReportId(soulReport.getId().toString()));
        } else if (soulReports.size() == 3) {
            //解除锁住
            paperListVo1.setIsLock(0);
            paperListVo2.setIsLock(0);
            paperListVo3.setIsLock(0);
            //设置报告id
            for (SoulReport soulReport : soulReports) {
                if (soulReport.getPaperid() == 1) {
                    paperListVo1.setReportId(soulReport.getId().toString());
                }if (soulReport.getPaperid() == 2) {
                    paperListVo2.setReportId(soulReport.getId().toString());
                }if (soulReport.getPaperid() == 3) {
                    paperListVo3.setReportId(soulReport.getId().toString());
                }
            }
            //soulReports.forEach(soulReport -> paperListVo3.setReportId(soulReport.getId().toString()));
        }

        //TODO
        //System.out.println(paperListVo);

        //返回集合对象
        List<PaperListVo> list = new ArrayList<>();
        list.add(paperListVo1);
        list.add(paperListVo2);
        list.add(paperListVo3);

        return list;
    }

    //TODO 公用方法*******************
    private void commendMethod1(PaperListVo paperListVo, int i) {
        //设置问卷编号
        paperListVo.setId(String.valueOf(i));
        //设置问卷名称
        paperListVo.setName(soulPaperMapper.selectById(i).getName());
        //设置封面
        paperListVo.setCover(soulPaperMapper.selectById(i).getCover());
        //设置级别
        paperListVo.setLevel(soulPaperMapper.selectById(i).getLevel());
        //设置星别
        paperListVo.setStar(Convert.toInt(soulPaperMapper.selectById(i).getStar()));


        QueryWrapper<SoulPaperQuestion> soulPaperQuestionQueryWrapper = new QueryWrapper<>();
        soulPaperQuestionQueryWrapper.eq("paperid", i);

        List<SoulPaperQuestion> soulPaperQuestions = soulPaperQuestionMapper.selectList(soulPaperQuestionQueryWrapper);

        List<QuestionsVo> questionsVoList = new ArrayList<>();
        //遍历题目1
        for (SoulPaperQuestion soulPaperQuestion : soulPaperQuestions) {
            //把题目加入QuestionsVo对象
            QuestionsVo questionsVo = new QuestionsVo();
            questionsVo.setId(soulPaperQuestion.getQuestionid().toString());
            questionsVo.setQuestion(soulQuestionMapper.selectById(soulPaperQuestion.getQuestionid()).getQuestion());

            //构造查询选项的条件
            QueryWrapper<SoulOptions> soulOptionsQueryWrapper = new QueryWrapper<>();
            soulOptionsQueryWrapper.eq("questionid", soulPaperQuestion.getQuestionid());
            //得到选项的集合
            List<SoulOptions> soulOptionsList = soulOptionsMapper.selectList(soulOptionsQueryWrapper);


            //得到选项的集合
            List<OptionsVo> optionsVolist = new ArrayList<>();

            //得到optionsVolist集合
            for (SoulOptions soulOptions : soulOptionsList) {
                OptionsVo optionsVo = new OptionsVo();
                optionsVo.setId(soulOptions.getId().toString());
                optionsVo.setOption(soulOptions.getOptions());
                optionsVolist.add(optionsVo);
            }
            questionsVo.setOptions(optionsVolist);
            questionsVoList.add(questionsVo);
        }
        paperListVo.setQuestions(questionsVoList);
    }

    /**
     * 提交问卷
     *
     * @param map
     * @return
     */
    public String submitTestPaper(Map<String, List<Answers>> map) {
        User user = UserThreadLocal.get();
        //计算得分
        Long score = 0L;
        Long questionid = 0L;
        //遍历获得对象

        Collection<List<Answers>> AnswersList = map.values();
        for (List<Answers> answers : AnswersList) {
            //试题ID
            for (Answers answer : answers) {
                questionid = Long.valueOf(answer.getQuestionId());
                //获得选项的字符串
                String option = answer.getOptionId();
                QueryWrapper<SoulOptions> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("questionid", questionid);
                queryWrapper.eq("id", option);
                //计算得分
                SoulOptions soulOptions1 = this.soulOptionsMapper.selectOne(queryWrapper);
                Long score1 = soulOptions1.getScore();
                score += score1;
            }
        }


//        for (SoulOptions soulOptions : values) {
//            //试题ID
//           questionid = soulOptions.getQuestionid();
//            //获得选项的字符串
//            String option = soulOptions.getOptions();
//            QueryWrapper<Object> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("option",option);
//            //计算得分
//            SoulOptions soulOptions1 = this.soulOptionsMapper.selectById(queryWrapper);
//            Long score1 = soulOptions1.getScore();
//            score+=score1;
//        }
        //判断做的是哪套试卷
        QueryWrapper queryWrapper = new QueryWrapper();
        //获得试卷ID
//        SoulOptions soulOptions = list.get(1);
//        Long questionid = soulOptions.getQuestionid();
        //查询做的哪套
        queryWrapper.eq("questionid", questionid);
        SoulPaperQuestion soulPaperQuestion = this.soulPaperQuestionMapper.selectOne(queryWrapper);
        Long paperid = soulPaperQuestion.getPaperid();
        System.out.println("该用户做的试卷是:" + paperid);
        System.out.println("该用户得分为:" + score);
        System.out.println("当前用户为:" + user.getId());
        //这个用户能否查到报告ID,有ID的话说明要重新测试需要更新得分
        QueryWrapper<SoulReport> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("userid", user.getId()).eq("paperid", paperid);
        SoulReport result = this.soulReportMapper.selectOne(queryWrapper2);

        if (ObjectUtil.isNotEmpty(result)) {
            //不为空就更新得分,最后将ID返回
            QueryWrapper<SoulReport> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("userid", UserThreadLocal.get().getId());
            SoulReport soulReport = new SoulReport();
            soulReport.setScore(score);
            soulReport.setUpdated(new Date(System.currentTimeMillis()));
            soulReportMapper.update(soulReport, queryWrapper1);

            //查询当前结果的ID返回
            QueryWrapper<SoulReport> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("userid", user.getId()).eq("paperid", paperid);
            SoulReport soulReport1 = soulReportMapper.selectOne(queryWrapper3);
            System.out.println("当前结果的ID为:" + soulReport1.getId());
            return soulReport1.getId().toString();
        }
        //如果查不到那就插入到数据库
        SoulReport soulReport = new SoulReport();
        soulReport.setUserid(UserThreadLocal.get().getId());
        soulReport.setPaperid(paperid);
        soulReport.setScore(score);
        soulReport.setCreated(new Date(System.currentTimeMillis()));
        soulReport.setUpdated(new Date(System.currentTimeMillis()));
        soulReportMapper.insert(soulReport);

        //查询当前结果的ID返回
        QueryWrapper<SoulReport> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("userid", user.getId()).eq("paperid", paperid);
        SoulReport soulReport1 = soulReportMapper.selectOne(queryWrapper1);
        return soulReport1.getId().toString();
    }
}
